import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import message from 'ant-design-vue/es/message'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import config from '@/config/defaultSettings'
import router from '@/router'
import qs from 'qs'
const baseUrl = config.baseUrl

// 创建 axios 实例
const request = axios.create({
	// API 请求的默认前缀
	baseURL: baseUrl,
	timeout: 6000 // 请求超时时间
})

const loginOut = () => {
	storage.set(ACCESS_TOKEN, undefined)
	router.replace({
		name: 'login'
	})
}

// 异常拦截处理器
const errorHandler = (error) => {
	error.response && notification.error({
		message: '错误',
		description: error.response.statusText
	})
	return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
	const parameterMethodArr = ['post', 'put', 'delete']
	const token = storage.get(ACCESS_TOKEN)
	if (config.method.toLowerCase() == 'get') {
		config.params = config.params || {}
		config.params.token = token
		config.paramsSerializer = (params) => {
			return qs.stringify(params, { arrayFormat: 'repeat' })
		}
	} else if (parameterMethodArr.includes(config.method.toLowerCase())) {
		config.url += `?token=${token}`
	}
	return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
	const configShowMessage = response.config.showMessage;
	const showMessage = (configShowMessage == undefined || configShowMessage == null) ? true : !!configShowMessage
	const { code, msg } = response.data;
	if (code == '200') {
		return response.data
	} else {
		(code == '403' || code == '401') && loginOut();
		showMessage && message.warning({
			content: msg
		})
		return Promise.reject('expectations error')
	}
}, errorHandler)

const installer = {
	vm: {},
	install(Vue) {
		Vue.use(VueAxios, request)
	}
}

export default request

export {
	installer as VueAxios,
	request as axios
}
